/**
* 检查字符串中是否包含姓名拼音
* @param {string} inputStr 要检查的字符串
* @param {string} namePinyin 姓名的拼音(可以包含空格分隔)
* @param {boolean} countOccurrences 是否返回出现次数(可选)
* @returns {string|number} 默认返回"出现"或"不出现",如果countOccurrences为true则返回次数
*/
function checkNamePinyin(inputStr, namePinyin, countOccurrences = false) {
// 处理拼音字符串:去除多余空格,转换为小写,并处理可能的变体
const processedPinyin = namePinyin.trim().toLowerCase().replace(/\s+/g, '\\s*');
// 创建正则表达式,考虑拼音可能被其他字符包围
const regex = new RegExp(`\\b${processedPinyin}\\b`, 'gi');
// 查找匹配
const matches = inputStr.match(regex);
if (countOccurrences) {
// 返回出现次数
return matches ? matches.length : 0;
} else {
// 返回是否出现
return matches ? "出现" : "不出现";
}
}
// 使用示例
const text = "张三和李四去吃饭,zhangsan 点了 pizza,lisi 要了面条。ZhangSan 最后付了钱。";
const name = "zhang san";
// 基本用法
console.log(checkNamePinyin(text, name)); // 输出: 出现
// 获取出现次数
console.log(checkNamePinyin(text, name, true)); // 输出: 2
// 测试用例
const testCases = [
{ text: "wanglei是我的朋友", name: "wang lei", expected: "出现", count: 1 },
{ text: "张三和李四", name: "zhang san", expected: "不出现", count: 0 },
{ text: "WANGLei 今天很开心", name: "wang lei", expected: "出现", count: 1 },
{ text: "王磊和王乐", name: "wang le", expected: "不出现", count: 0 },
{ text: "zhang san,zhangsan,zhang-san", name: "zhang san", expected: "出现", count: 3 }
];
testCases.forEach((test, index) => {
console.log(`测试用例 ${index + 1}:`);
console.log(`检查结果: ${checkNamePinyin(test.text, test.name)} (预期: ${test.expected})`);
console.log(`出现次数: ${checkNamePinyin(test.text, test.name, true)} (预期: ${test.count})`);
console.log("-------------------");
});